package com.daotu.psy.common.mybatis.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Map;

/**
 * MyBatis-Plus,List<DictData>处理类
 *
 * @author jacky
 */
public abstract class BaseMapTypeHandler<T> extends BaseTypeHandler<Map<String, T>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<String, T> parameter, JdbcType jdbcType) throws SQLException {
        String content = CollUtil.isEmpty(parameter) ? JSONUtil.toJsonStr(Collections.emptyMap()) : JSONUtil.toJsonStr(parameter);
        ps.setString(i, content);
    }

    @Override
    public Map<String, T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String content = rs.getString(columnName);
        return (StrUtil.isBlank(content) ? Collections.emptyMap() : JSONUtil.toBean(content, this.specificType().getType(), true));
    }

    @Override
    public Map<String, T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String content = rs.getString(columnIndex);
        return (StrUtil.isBlank(content) ? Collections.emptyMap() : JSONUtil.toBean(content, this.specificType().getType(), true));
    }

    @Override
    public Map<String, T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String content = cs.getString(columnIndex);
        return (StrUtil.isBlank(content) ? Collections.emptyMap() : JSONUtil.toBean(content, this.specificType().getType(), true));
    }

    protected abstract TypeReference<Map<String, T>> specificType();
}
